import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
public class MyHttpResponse {
    private OutputStream outputStream;
    public MyHttpResponse(OutputStream outputStream) {
        this.outputStream = outputStream;
    }
    public void sendRedirect(String uri){
        //判断uri是否存在
        //不存在 返回404
        //存在 返回目标资源数据
        File file = new File(System.getProperty("user.dir") + "/WebContent" + uri);
        if(file.exists()){
            //返回目标资源数据
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
                byte[] bytes = new byte[(int)file.length()];
                fileInputStream.read(bytes);
                String result = new String(bytes);
                String response = getResponseMessage("200",result);
                this.outputStream.write(response.getBytes());
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }else{
            //返回404
            try {
                String error = getResponseMessage("404","404 File Not Found");
                this.outputStream.write(error.getBytes());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    public String getResponseMessage(String code,String message){
        return "HTTP/1.1 "+ code+"\r\n"
                +"Content-type: text/html\r\n"
                +"Content-Length: "+message.length()
                +"\r\n"
                +"\r\n"
                +message;
    }
}
